package com.talent.jiwen.http.common;

import android.text.TextUtils;

import com.google.gson.GsonBuilder;
import com.talent.jiwen.BuildConfig;
import com.talent.jiwen.http.api.EducationApi;
import com.talent.jiwen.http.api.TiKuApi;
import com.talent.jiwen.util.LogUtil;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;


public class ApiRetrofit {

    public TiKuApi TikuApiService;
    public EducationApi mEducationApi;

    public static final String TIKU_URL = "http://120.77.154.227/testweb1/home/";
    //********************外网IP***************************//
    public static final String EDU_URL = "http://118.31.64.51:80/api/";
    public static final String EDU_WEB_URL = "http://www.uixkid.com"; //网页地址
    //********************内网IP***************************//
//    public static  String EDU_URL = "http://192.168.0.160:8080/api/";
//    public static  String EDU_WEB_URL = "http://192.168.0.160:8080";

    public TiKuApi getTikuApiService() {
        return TikuApiService;
    }
    public EducationApi getEducationApiService() {
        return mEducationApi;
    }

    /**
     * 加入 OkHttp 配置，通过OkHttpClient 可以配置：链接超时时间，缓存，拦截器等
     */
    public ApiRetrofit() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.sslSocketFactory(SSLSocketClient.getSSLSocketFactory());
        builder.hostnameVerifier(SSLSocketClient.getHostnameVerifier());
        builder.connectTimeout(30, TimeUnit.SECONDS);
        builder.readTimeout(30, TimeUnit.SECONDS);
        builder.writeTimeout(30, TimeUnit.SECONDS);

        //添加公共参数拦截器
        if (BuildConfig.DEBUG) {
            HttpLoggingInterceptor logging = new HttpLoggingInterceptor(
                    new HttpLoggingInterceptor.Logger() {
                        @Override
                        public void log(String message) {
                            if (TextUtils.isEmpty(message)) return;
                            String s = message.substring(0, 1);
                            //如果收到响应是json才打印
                            if ("{".equals(s) || "[".equals(s)) {
                                LogUtil.e("log", message);
                            }
                        }
                    });
            logging.setLevel(HttpLoggingInterceptor.Level.BODY);

            builder.addInterceptor(logging);
        }
        //错误重连
        builder.retryOnConnectionFailure(true);

        /**
         * 2,创建一个完整的 Retrofit 实例，并且完成相关的配置
         *   如果配合 rxjava 使用，添加两行代码
         */

        OkHttpClient okHttpClient = builder.build();
        Retrofit retrofit_tiku = new Retrofit.Builder()
                .baseUrl(TIKU_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create(new GsonBuilder().create()))
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(okHttpClient)
                .build();

        /**
         * 获取接口实例
         * 创建了一个RetrofitServiceManager类，该类采用单例模式，在私有的构造方法中，
         * 生成了Retrofit 实例，并配置了OkHttpClient和一些公共配置。
         * 提供了一个create（）方法，生成接口实例，接收Class范型，
         * 因此项目中所有的接口实例Service都可以用这个来生成，代码如下：
         */
        TikuApiService = retrofit_tiku.create(TiKuApi.class);


        Retrofit retrofit_education = new Retrofit.Builder()
                .baseUrl(EDU_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(okHttpClient)
                .build();
        mEducationApi = retrofit_education.create(EducationApi.class);

        /*
        * 带token的请求
        * */
        OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
        // httpClientBuilder.connectTimeout(10000, TimeUnit.SECONDS);

        /**
         *  拦截器
         */
        httpClientBuilder.addInterceptor(new Interceptor() {
            @Override
            public okhttp3.Response intercept(Chain chain) throws IOException {
                Request request = chain.request();
                Request newRequest = request.newBuilder()
                        //对所有请求添加请求头
                        .header("mobileFlag", "adfsaeefe").addHeader("type", "4")
                        .method(request.method(), request.body())
                        .build();
                return chain.proceed(newRequest);
            }
        });
    }
}


